﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using vJine.Core.IoC;

namespace vJine.Core.ORM.Adapters {
    /// <summary>
    /// MySQL 数据库适配器类型
    /// </summary>
    public partial class MySQL : IDbAdapter<MySQL> {

        static MySQL() {
            MySQL.Init_Keywords();
            MySQL.Init_TypeMap();
        }
        /// <summary>
        /// 实例化MySQL数据库适配器类型
        /// </summary>
        public MySQL() {
            this.Name = Class<MySQL>.Name;

            this.ParamPrefix = "@";
            this.GetDateTime = "Select NOW()";

            this.QuoteOpen = "`";
            this.QuoteClose = "`";

            this.NULL = " NULL";
            this.NOT_NULL = " NOT NULL";
            
            this.KeyWords = MySQL._KeyWords;
        }
        /// <summary>
        /// 生成查询数据命令
        /// </summary>
        /// <typeparam name="Tentity">实体类型</typeparam>
        /// <param name="max">最大记录数</param>
        /// <param name="fields">属性集合（要查询的属性）</param>
        /// <param name="table_name">表名</param>
        /// <param name="where">条件表达式</param>
        /// <param name="orders">排序字段</param>
        /// <returns></returns>
        public override DbCommand PrepareQuery<Tentity>(int max, List<Class<Tentity>.Property> fields, string table_name, Class<Tentity>.Where where, List<Class<Tentity>.Property> orders) {
            int pCounter = 0;
            StringBuilder sbCmd = new StringBuilder();
            DbCommand dbCmd = this.Conn.CreateCommand();

            sbCmd.Append("Select ");

            //Fields
            this.ToSelectString<Tentity>(dbCmd, sbCmd, fields);

            sbCmd.Append(" From ").Append(table_name);

            //Where
            if(where != null) {
                sbCmd.Append(" Where ");
                this.ToWhereString<Tentity>(
                    dbCmd, sbCmd, where, ref pCounter, false);
            }

            //Order By
            if(orders != null && orders.Count > 0) {
                sbCmd.Append(" Order By ");
                for(int j = 0, len_j = orders.Count - 1; j <= len_j; j++) {
                    Class<Tentity>.Property order_j = orders[j];
                    if(order_j.IsASC == null) {
                        continue;
                    }
                    sbCmd.Append(order_j.Name).Append(order_j.IsASC.Value ? " ASC" : " DESC");
                    if(j < len_j) {
                        sbCmd.Append(",");
                    }
                }
            }

            if(max > 0) {
                sbCmd.Append(" Limit ").Append(max.ToString());
            }

            dbCmd.CommandText = sbCmd.ToString();
            return dbCmd;
        }
    }
}
